from pathlib import Path
import shutil

class FileOrganizer:
    def __init__(self, source_dir, target_dir, file_types):
        """
        文件整理工具
        :param source_dir: 源目录路径
        :param target_dir: 目标目录路径
        :param file_types: 文件类型（字符串或列表）
        """
        self.source_path = Path(source_dir)
        self.target_path = Path(target_dir)
        if isinstance(file_types, str):
            self.extensions = [ext.strip().lstrip('.') for ext in file_types.split(",") if ext.strip()]
        else:
            self.extensions = [ext.lstrip('.') for ext in file_types if ext]

    def validate_and_prepare(self):
        """验证源目录~并创建目标目录"""
        if not self.source_path.is_dir():
            raise NotADirectoryError(f"错误：源路径不是有效目录 - {self.source_path}")
        self.target_path.mkdir(parents=True, exist_ok=True)

    def move_files(self):
        """执行文件移动操作"""
        self.validate_and_prepare()
        processed_files = 0
        for ext in self.extensions:
            for src_file in self.source_path.rglob(f"*.{ext}"):
                if not src_file.is_file():
                    continue
                dest_file = self._generate_unique_name(src_file.name)
                try:
                    shutil.move(str(src_file), str(dest_file))
                    print(f"已移动: {src_file} -> {dest_file}")
                    processed_files += 1
                except Exception as e:
                    print(f"移动失败: {src_file} -> {dest_file}，原因: {e}")
        print(f"\n移动完成！共处理 {processed_files} 个文件")
        return processed_files

    def _generate_unique_name(self, filename):
        """生成唯一的文件名避免冲突"""
        dest_file = self.target_path / filename
        base, suffix = dest_file.stem, dest_file.suffix
        counter = 1
        while dest_file.exists():
            dest_file = self.target_path / f"{base}_{counter}{suffix}"
            counter += 1
        return dest_file

if __name__ == "__main__":
    try:
        FileOrganizer(
            source_dir=r"E:\行业标准\two\订单（订单评审表）",
            target_dir=r"E:\行业标准\two\all订单评审表",
            file_types="xlsx,docx,pdf"
        ).move_files()
    except Exception as e:
        print(f"发生错误: {e}")